/*
 * @Description:
 * @Version: 2.0
 * @Autor: zss
 * @Date: 2024-07-12 10:16:26
 * @LastEditors: swc
 * @LastEditTime: 2024-09-06 16:22:00
 */
import { Tsrv, ifs, ts } from '@/services';
import { N_HomePage } from './type';

class T_cmd {
  // 主组件箱
  private compBox: ifs.I_compBox;

  // 主组件ID
  private compID: string;

  // 主组件实例
  private self: N_HomePage.HomePage;
  // 主组refs

  // 主组件created里初始化
  public async init(self: any, compBoxInfo: ifs.I_compBoxInfo) {
    this.self = self;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
    this.getTitles();
    this.getConfigShowArray();
    // this.self.showArray = obj.showArray;
    // this.initHomeCustomTypeTitles(obj.configShowArray);
    // this.filterByPms(await this.getShowArray(await this.getConfigShowArray()));
  }

  public getTcmd(): T_cmd {
    return this;
  }

  private async initHomeCustomTypeTitles(P_configShowArray: any[]) {
    const [b, res, rows, err] = await this.doLoadData(
      // Tsrv.globalVar.funName.SYS_PROPERTY_TYPE_DETAIL,
      // Tsrv.globalVar.funName.SYS_PROPERTY_TYPE_DETAIL,
      '_sys_property_type_detail',
      '_sys_property_type_detail',
      { _sys_property_type_id: { $in: ['519553100764160000'] } }
    );
    if (!b) {
      this.self.$msg(err ?? res.msg);
      return;
    }
    rows.forEach((e: any, idx: number) => {
      this.self.homeCustomTypeTitles.set(e.f_value, e);
    });
    this.initConfigShowArray(P_configShowArray);
  }

  private initConfigShowArray(P_configShowArray: any[]) {
    const obj = Tsrv.utils.groupBy(P_configShowArray, 'ftypeid');
    for (const csa in obj) {
      for (const c in obj[csa]) {
        if (obj[csa][c]['ftypeid'] === 1) {
          obj[csa][c]['f_name'] = this.self.homeCustomTypeTitles.get(
            obj[csa][c]['homepage_custom_component_types']
          )['f_text'];
        }
      }
    }

    this.self.configShowArray = obj;
  }

  // 权限过滤
  private filterByPms(P_arr: any) {
    const L_funsFunIdArr = [];
    P_arr.configShowArray.forEach((e: any) => {
      e.FTypeID !== 1 && L_funsFunIdArr.push(e['_sys_fun_id']);
    });
    // this.$lib.httpRequest
    //   .query({
    //     fields: '*',
    //     sqlBody: `from view_permission_action where roleObj_objId = ${this.userID
    //       } and aspectELE_title = "browse" and funs_funId in (${L_funsFunIdArr.join(
    //         ','
    //       )})`
    //   })
    // .then((res: any) => {
    //   // 根据权限过滤抽屉配置数组configShowArray
    //   const L_a = [];
    //   P_arr.configShowArray.forEach((e: any) => {
    //     if (e.FTypeID !== 1) {
    //       this.$utils.every(res.data.rows, (item: any) => {
    //         if (item['funs_funId'] === e['_sys_fun_id']) {
    //           return item['action_enable'] === 1;
    //         }
    //         return true;
    //       }) && L_a.push(e);
    //     } else {
    //       L_a.push(e);
    //     }
    //   });
    //   this.initConfigShowArray(L_a);
    //   // 根据权限过滤首页显示组件数组showArray
    //   const L_b = [];
    //   P_arr.showArray.forEach((e: any) => {
    //     if (e.FTypeID !== 1) {
    //       this.$utils.every(res.data.rows, (item: any) => {
    //         if (item['funs_funId'] === e['_sys_fun_id']) {
    //           return item['action_enable'] === 1;
    //         }
    //         return true;
    //       }) && L_b.push(e);
    //     } else {
    //       L_b.push(e);
    //     }
    //   });
    //   this.showArray = L_b;
    //   // 如果有被勾选但已被管理员取消授权的组件删除被勾选的数据
    //   const L_delArr = [];
    //   P_arr.showArray.forEach((e: any) => {
    //     if (e.FTypeID !== 1) {
    //       !this.$utils.some(
    //         L_a,
    //         (item: any) => item['_sys_fun_id'] === e['_sys_fun_id']
    //       ) && L_delArr.push(e);
    //     }
    //   });
    //   if (L_delArr.length > 0) {
    //     const L_removeRecords = [];
    //     L_delArr.forEach((e: any) => {
    //       L_removeRecords.push(e.shpsuId);
    //     });
    //     // this.save(this.tableName, { removeRecords: L_removeRecords });
    //   }
    // });
  }

  private getShowArray(rs: any) {
    return this.doLoadData('_sys_homepage_set_user', '_sys_homepage_set_user', {
      _sys_user_id: { $eq: Tsrv.getUserID() }
    }).then(([b, res, rows, msg]) => {
      const L_a = [];
      let L_b = [];

      const L_arr = [];
      rs.forEach((e: any, idx: number) => {
        const L_d = Tsrv.utils.find(rows, i => i['master_bill_id'] === e.id);
        if (L_d) {
          L_arr.push({ ...e, fsn: L_d.fsortno, shpsuId: L_d.id });
          L_a.push({
            ...e,
            isShow: true,
            shpsuId: L_d.id,
            fsn: L_d.fsortno
          });
        } else {
          L_a.push({ ...e, isShow: false });
        }
      });

      L_b = Tsrv.utils.sortBy(L_arr, 'fsn');
      // return { configShowArray: L_a, showArray: L_b };
      this.self.showArray = L_b;
      this.initHomeCustomTypeTitles(L_a);
    });
  }

  // 主页展示分组类型（字段下拉列表）
  private async getTitles() {
    const [b, res, rows, err] = await this.doLoadData(
      // Tsrv.globalVar.funName.SYS_PROPERTY_TYPE_DETAIL,
      // Tsrv.globalVar.funName.SYS_PROPERTY_TYPE_DETAIL,
      '_sys_property_type_detail',
      '_sys_property_type_detail',
      { _sys_property_type_id: { $in: ['519549527061962752'] } }
    );
    if (!b) {
      this.self.$msg(err ?? res.msg);
      return;
    }
    rows.forEach((e: any, idx: number) => {
      this.self.titles.set(e.f_value, e);
    });
  }

  private getConfigShowArray() {
    this.doLoadData('_sys_homepage_set', '_sys_homepage_set').then(
      ([b, res, rows, err]) => {
        if (!b) {
          this.self.$msg(err ?? res.msg);
        }
        this.getShowArray(rows);
      }
    );
  }

  private loadFilterList(
    field: string[],
    funName: string,
    filter = {}
  ): Promise<
    Array<{
      [key: string]: any;
    }>
  > {
    const gpfd: ts.T_GPFD = new ts.T_GPFD();
    gpfd
      .setLang(this.self.$i18n.locale || 'en-US')
      .setFunName(funName)
      .setTableName(funName)
      .setDbType(Tsrv.globalVar.dbType.MYSQL);
    gpfd.setFilter(filter).setAgreedFields(...field);

    return new Promise((resolve, reject) => {
      Tsrv.getData<any, ifs.I_GPFD>(gpfd)
        .then(r => {
          const [b, res, rows, msg] = r;
          resolve(rows);
        })
        .catch(err => {
          this.self.$msg(err);
        });
    });
  }

  public doLoadData(funName: string, tableName: string, filter: object = {}) {
    const gpd = new ts.T_getPartDataArg();
    gpd.setFilter(filter);
    gpd.setFunName(tableName);
    gpd.setTableName(tableName);
    gpd.setDbType(Tsrv.globalVar.dbType.MYSQL);
    gpd.setLang(this.self.$i18n.locale);
    gpd.setPage(1, 99999);
    gpd.setRule({} as ifs.I_rule);

    return Tsrv.getData(gpd);
  }

  public saveConfigShowArray(updateRecords: Array<Array<ifs.I_fv>>) {
    const ctd = new ts.T_ctdArg();
    ctd
      .setFunName('_sys_homepage_set_user')
      .setTableName('_sys_homepage_set_user')
      .setDbType(Tsrv.globalVar.dbType.MYSQL)
      .setRule({} as ifs.I_rule);
    const ctdUpdDatas: ifs.I_ctdUpdData[] = [];
    updateRecords.forEach(el => {
      const filter = {};
      const ctdUpdData = new ts.T_ctdUpdData();
      ctdUpdData.setDataRule({} as ifs.I_rule).setFileInfo({});
      const find = Tsrv.utils.find(el, item => item.field === 'id');
      if (!Tsrv.noValue(find)) {
        filter['id'] = find.value;
      }
      ctdUpdData.setFilter(filter);
      ctdUpdData.setRowData(...el.filter(item => item.field !== 'id'));
      ctdUpdDatas.push(ctdUpdData);
    });

    ctd.setUpdRecDataMany(...ctdUpdDatas);
    Tsrv.batRows(ctd).then(([b, res, msg]) => {
      if (!b) {
        this.self.$msg(msg);
      } else {
        this.getConfigShowArray();
      }
    });
  }
}
interface I_cmd extends T_cmd {}
export { I_cmd, T_cmd };
